package top.wanzc.java.basic.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

class OrderDelay implements Delayed {
	
	private String orderId;
	
	private long timeout;
	
	OrderDelay(String orderId, long timeout) {
		this.orderId = orderId;
		this.timeout = timeout + System.nanoTime();
	}

	@Override
	public int compareTo(Delayed other) {
		if (this == other) {
			return 0;
		}
		OrderDelay t = (OrderDelay) other;
		long d = (getDelay(TimeUnit.NANOSECONDS) - t
                .getDelay(TimeUnit.NANOSECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
	}
	
	void print() {
		System.out.println("orderId : " + orderId + " timeout.");
	}
}

public class DelayQueueDemo {
	
	public static void main(String[] args) throws Exception {
		List<String> list = new ArrayList<String>(); 
		list.add("00000001");  
        list.add("00000002");  
        list.add("00000003");  
        list.add("00000004");  
        list.add("00000005");
        DelayQueue<OrderDelay> queue = new DelayQueue<OrderDelay>(); 
        long start = System.currentTimeMillis(); 
        for (int i = 0; i < 5; i++) {
        	queue.put(new OrderDelay(list.get(i), TimeUnit.NANOSECONDS.convert(3,TimeUnit.SECONDS)));  
        	 queue.take().print();  
             System.out.println("After " + (System.currentTimeMillis()-start) + " MilliSeconds"); 
        }
	}

}
